const xss = require('xss')
const {exec} = require('../db/mysql.js')

//获取博客列表
const getList = async (author, keyword) => {
  let sql = `select * from blogs where 1=1 `
  if (author){
    sql += `and author='${author}' `
  }
  if (keyword){
    sql += `and title like'%${keyword}%' `
  }
  sql += `order by createtime desc`
  return await exec(sql)
}
//根据id 获取博客详细
const getDetail = async (id) => {
  const sql = `select * from blogs where id ='${id}' `
  const rows = await exec(sql)
  return  rows[0]
  
}
//新建一个博客
const newBlog = async (blogData={})=>{
  console.log(blogData)
  const title = xss(blogData.title)
  const content = xss(blogData.content)
  const author = xss(blogData.author)
  const createTime = Date.now()
  console.log(blogData)
  const sql = `insert into blogs(title,content,author,createTime) values('${title}','${content}','${author}','${createTime}')`
  const  insertData =exec(sql)
  return{
      id: insertData.insertId
  }
}

//更新博客
const updateBlog= async (id,blogData={})=>{
  const title = blogData.title
  const content = blogData.content
  const sql = `update blogs set title='${title}',content='${content}' where id=${id} `
  const updateData= await exec(sql)
  if (updateData.affectedRows >0){
      return true
    }
    return false
}

const delBlog = async (id,author)=>{
  const sql = `delete from blogs where id=${id} and author='${author}'`
  return delData =exec(sql)
  if (delData.affectedRows > 0){
    return true
  }
    return  false
}

module.exports = {
  getList,
  getDetail,
  newBlog,
  updateBlog,
  delBlog,
}
